package com.movitech.mobile.cz.base.sys.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.IdGenUtils;
import com.movitech.mobile.cz.base.common.util.StringUtils;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.sys.bizvo.UserRequestVO;
import com.movitech.mobile.cz.base.sys.entity.SysUser;
import com.movitech.mobile.cz.base.sys.entity.ext.ExtSysUser;
import com.movitech.mobile.cz.base.sys.entity.ext.SysUserRequestVO;
import com.movitech.mobile.cz.base.sys.mapper.SysUserMapper;
import com.movitech.mobile.cz.base.sys.mapper.ext.ExtSysUserMapper;
import com.movitech.mobile.cz.base.sys.service.SysUserService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-02-28
 */
@Service("sysUserService")
@Transactional
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private ExtSysUserMapper extSysUserMapper;

    @Override
    public RestReturnResult<SysUser> saveUserRequestVo(UserRequestVO userRequestVo) {
        RestReturnResult<SysUser> hResult = RestReturnResult.error();
        SysUser user=new SysUser();
        user.setId(IdGenUtils.uuid());
        BeanUtils.copyProperties(userRequestVo,user);
        user.setLoginName(userRequestVo.getUserName());
        user.setName(userRequestVo.getUserName());
        user.setLoginFlag(CommonConstants.YES_LOGIN);
        user.setPassword(userRequestVo.getPassword());
        user.setUserType(CommonConstants.EXTERNAL_USER);
        user.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
        if(super.insert(user)){
            hResult= RestReturnResult.success();
        }
        hResult.setData(user);
        return hResult;
    }

    @Override
    public SysUser getSysUserByUserName(String userName) {
        EntityWrapper wrapper = new EntityWrapper<>();
        SysUser sysUser=new SysUser();
        sysUser.setLoginName(userName);
        sysUser.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
        wrapper.setEntity(sysUser);
        sysUser=super.selectOne(wrapper);
        return sysUser;
    }

    @Override
    public String createPassword() {
        String a = "0123456789";
        char[] rands = new char[5];
        for (int i = 0; i < rands.length; i++)
        {
            int rand = (int) (Math.random() * a.length());
            rands[i] = a.charAt(rand);
        }
        StringBuffer sb=new  StringBuffer();
        for(int i=0;i<rands.length;i++){
            sb.append(rands[i]);
        }
        return "z"+sb;
    }

    @Override
    public ExtSysUser getUserByLoginName(String loginName) {
        ExtSysUser user = extSysUserMapper.getUserByLoginName(loginName);
        return user;
    }

    @Override
    public String getSysUserNameByIds(String ids) {
        if(StringUtils.isBlank(ids)){
            return null;
        }
        List<String> names = new ArrayList<>();
        for(String id : ids.split(",")){
            if(StringUtils.isNotEmpty(id)){
                names.add(selectById(id).getName());
            }
        }

        return StringUtils.arr2String(names.toArray());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public RestReturnResult<Object> batchAdd(List<SysUserRequestVO> sysUserRequestVOList) {
        RestReturnResult<Object> hResult = RestReturnResult.error();
        try {
            if(sysUserRequestVOList!=null&&sysUserRequestVOList.size()>0){
                for(SysUserRequestVO sysUserRequestVO:sysUserRequestVOList){
                    if(StringUtils.isEmpty(sysUserRequestVO.getJobNumber()))continue;
                    SysUser sysUserOld=this.selectById(sysUserRequestVO.getJobNumber());
                    if(sysUserOld==null){
                        SysUser sysUser=new SysUser();
                        sysUser.setPassword(DigestUtils.md5Hex("abc123456"));//默认abc123456
                        sysUser.setUserType(CommonConstants.INNER_USER);
                        sysUser.setLoginFlag(CommonConstants.YES_LOGIN);
                        sysUser.setId(sysUserRequestVO.getJobNumber());
                        sysUser.setLoginName(sysUserRequestVO.getJobNumber());
                        sysUser.setUserCode(sysUserRequestVO.getJobNumber());
                        sysUser.setName(sysUserRequestVO.getName());
                        sysUser.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
                        this.insert(sysUser);
//                    }else{
//                        if(!sysUserOld.getName().equals(sysUserRequestVO.getName())){
//                            sysUserOld.setName(sysUserRequestVO.getName());
//                            sysUserOld.setUpdateDate(new Date());
//                            sysUserOld.setUpdateBy(UserUtils.getCurrentUserId());
//                            this.updateById(sysUserOld);
//                        }
                    }
                }
            }
            hResult = RestReturnResult.success();
        }catch (RuntimeException e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return hResult;
    }
}
